#include "timer.h"
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_rcc.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx.h"
#include <stdlib.h>
#include "math.h"

#include "sequencefilter.h"
#include "FactoryPID.h"
#include "usart.h"
#include "oled.h"
#include "adc.h"
#include "pwm.h"
#include "key.h"
//--------------------------------------------------------------------------------------------//
// int count_timer1 = 0;
// int count_timer2 = 0;
// int count_timer3 = 0;
// int count_timer4 = 0;
// int count_timer5 = 0;
// int count_timer8 = 0;

#define      a     15.58
#define      b     0.0001732
#define      c     -28.65
#define      d     -0.00291

#define STEER_PSC 1000
CAR_TURN(motor,4,1);

extern __IO uint16_t ADC_ConvertedValue;
MAKE_FUNC_PID_S(pid,float,-1000,1000);


MAKE_SEQFILTER_MED(lvbo,int,10);


float temp;
int tem = 0;
float wei = 0.0;
char str[4];
float ret = 0.0;

/**
  * @brief  定时器1初始化
  * @param  arr 初值
  *         psc 分频系数
  * @retval 无
  */
void Timer1_Init(u16 arr,u16 psc)
{
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStrecture;
	NVIC_InitTypeDef NVIC_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);/*使能定时器1的时钟*/


	NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_TIM10_IRQn;/*定时器1的中断通道使能*/
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;/*定时器1的中断通道使能*/
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;/*抢占优先级*/
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;/*响应优先级*/
	NVIC_Init(&NVIC_InitStructure);/*配置中断分组，并使能中断*/

	TIM_TimeBaseInitStrecture.TIM_Period = arr;/*重装载寄存器*/
	TIM_TimeBaseInitStrecture.TIM_Prescaler = psc;/*预分配*/
	TIM_TimeBaseInitStrecture.TIM_ClockDivision = TIM_CKD_DIV1;/*时钟分频*/
	TIM_TimeBaseInitStrecture.TIM_CounterMode = TIM_CounterMode_Up;/*向上计数*/
	TIM_TimeBaseInitStrecture.TIM_RepetitionCounter = 0;/*重复计数寄存器*/
	TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStrecture);/*初始化*/

	TIM_ClearFlag(TIM1,TIM_FLAG_Update);/*清更新标志位*/
	TIM_ITConfig(TIM1,TIM_IT_Update,ENABLE);/*使能中断*/
	TIM_Cmd(TIM1,ENABLE);/*使能计数*/

}




void TIM1_UP_TIM10_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET){//检查指定的TIM中断发生与否:TIM 中断源 
		TIM_ClearITPendingBit(TIM1, TIM_IT_Update);//清除TIMx的中断待处理位:TIM 中断源 
/***************在此处添加中断执行内容******************/
		lvboSet(ADC_ConvertedValue);
//		
//		printf("d:%d\r\n",lvboGet());
		
		
		if(lvboGet() > 1600){
			temp = 11.0;
		}
		else if(lvboGet() < 210){
			temp = -10.0;
		}
		else {
			temp = a*exp(b*lvboGet()) + c*exp(d*lvboGet()) - 11;
		}
		
		
		tem = temp * 10;
		temp = tem / 10.0;
		
//		car_motor_turn(0,1);
//		OLED_ShowNum(0,4,temp,8);

		ret = pid(temp - wei, 0.03,  0, 0.4, 0);//ret = pid(temp-3-.0, 0.002, 0.0001, 1, 0);
//		ret = pid(temp, 0.03,  0.0002, 0.2, 0);
		
		if((ret >= -0.1)&&(ret <= 0.1)){
			car_motor_turn(0,1);
		}
		else{
			car_motor_turn(ret,1);
		}
		
    }

}

